<div class="layui-fluid layui-layout-admin">
	<fieldset class="layui-elem-field layui-field-title" style="margin-top: 20px;">
		<legend class="title"></legend>
	</fieldset>

	<form class="layui-form" action="">

		<div class="layui-form-item">
			<label class="layui-form-label">属性名称</label>
			<div class="layui-input-inline">
				<input type="text" name="name" autocomplete="off" placeholder="请输入属性名称" class="layui-input" value="">
			</div>
		</div>

		<div class="layui-form-item">
			<label class="layui-form-label">上级属性</label>
			<div class="layui-input-inline">
				<select name="pid">

				</select>
			</div>
		</div>

		<div class="layui-form-item">
			<div class="layui-input-block">
				<div class="layui-footer">
					<input type="hidden" name="id" value="0" />
					<input type="hidden" name="list_table_name" value="attribute-list" />
					<button class="layui-btn" lay-submit lay-filter="LAY-send-submit">立即提交</button>
				</div>
			</div>
		</div>
	</form>
</div>

<script type="text/html" template lay-done="layui.data.sendParams(d.params)">
</script>

<script>
	layui.data.sendParams = function(params) {
		console.log(params);
		layui.use(['form', 'upload'], function() {
			let $ = layui.jquery,
				form = layui.form,
				upload = layui.upload,
				router = layui.router();

			let _index = layer.load();
			$(".layui-form").attr('action', layui.setter.API_HOST + 'admin/attribute/save')
			let _attribute_id = params.id | 0;
			$(".title").text((_attribute_id > 0 ? '编辑' : '添加') + '属性');

			if (_attribute_id) {
				layui.admin.req({
					url: layui.setter.API_HOST + 'admin/attribute/save',
					data: {
						id: _attribute_id
					},
					done: function(res) {
						layer.close(_index);
						if (res.code == 0) {
							$("input[name='name']").val(res.data.name);
							$("input[name='id']").val(res.data.id);

							get_attribute_list(res.data.pid);
						} else {
							layer.msg('请求失败', {
								icon: 5
							})
						}
					}
				});
			} else {
				get_attribute_list(0);
			}

			function get_attribute_list(_pid) {
				layui.admin.req({
					url: layui.setter.API_HOST + 'admin/attribute/attribute_level_format',
					data: {
						id: _attribute_id
					},
					done: function(res) {
						layer.close(_index);
						if (res.code == 0) {
							let _html = [];
							_html.push('<option value="0">请选择</option>');
							$.each(res.data, function(i, d) {
								if (_pid == d.id) {
									_html.push('<option value="' + d.id +
										'" selected>' + d.name + '</option>');
								} else {
									_html.push('<option value="' + d.id + '">' + d
										.name + '</option>');
								}
							});
							$("select[name='pid']").html(_html.join(''));
							form.render();
						}
					}
				});
			}
		});
	}
</script>
